#include "qtactiveobject.h"

QtActiveObject::QtActiveObject()
    : done ( new QActiveMessage)
{
    start();
}

// Shut down: send sentinel and wait for queue to drain
QtActiveObject::~QtActiveObject()
{
    send( done );
    wait();
    quit();
}

void QtActiveObject::send(QActiveMessage * msg)
{
    // TODO Mutex
    que_mutex.lock();
    mq.push(msg);
    int sz = mq.size();
    que_mutex.unlock();
    qDebug("QtActiveObject: Que size %d", sz);
    start();
}

void QtActiveObject::run()
{
    que_mutex.lock();

    QActiveMessage* msg = mq.front();
    if (mq.empty()) msg = 0;
    que_mutex.unlock();


    if (msg == done || msg == 0) return;

    while( msg && msg != done ) {
        msg->Execute();
        delete msg;
        // Go to next
        que_mutex.lock();
        mq.pop();
        msg = mq.front();
        int sz = mq.size();
        que_mutex.unlock();
        qDebug("QtActiveObject: Que size now %d", sz);
    }
}
